import { createRouter, createWebHistory } from 'vue-router'

import { useAuthStore } from '../store/auth'
import { allRoles } from '../config/permissions'
import { ElMessage } from 'element-plus'
// 占位组件
const Placeholder = () => import('@/views/Developing.vue')

/**
 * 路由配置
 *
 * 认证配置需要设置meta字段, 默认为公开访问
 *
 * meta.requireAuth为true则需要登录
 *
 * meta.roles为允许的角色, meta.roles == undefined时表示所有角色可访问
 */
const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/auth/Login.vue'),
    },
    {
        path: '/',
        name: 'Home',
        component: () => import('@/views/Home.vue'),
        meta: { requiresAuth: true } // 访问此路由需要认证
    },
    {
        path: '/data-initialization',
        name: 'DataInitialization',
        component: () => import('@/views/initialization/DataInitialization.vue'),
        meta: { requiresAuth: true }
    },

    // Funds
    { path: '/funds', component: () => import('@/views/funds/FundList.vue'), meta: { requiresAuth: true } },
    { path: '/companies', component: () => import('@/views/funds/CompanyList.vue'), meta: { requiresAuth: true } },
    { path: '/managers', component: () => import('@/views/funds/ManagerList.vue'), meta: { requiresAuth: true } },
    { path: '/portfolios', component: () => import('@/views/funds/PortfolioList.vue'), meta: { requiresAuth: true } },
    { path: '/fund-data-hub', component: () => import('@/views/funds/FundDataHub.vue'), meta: { requiresAuth: true } },
    { path: '/fund-profile/:fundCode', name: 'FundProfile', component: () => import('@/views/funds/FundProfile.vue'), meta: { requiresAuth: true } },


    // User
    {
        path: '/users',
        name: 'UserManagement',
        component: () => import('@/views/user/UserManagement.vue'),
        meta: { requiresAuth: true }
    },

    // 必须在最后
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/NotFound.vue')
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
    const authStore = useAuthStore();
    const isAuthenticated = !!authStore.state.user;
    const requiredRoles = to.meta?.roles;

    // 检查路由是否需要认证
    if (to.meta.requiresAuth) {
        if (isAuthenticated) {
            // 如果用户已登录，检查角色权限
            if (requiredRoles && requiredRoles.length > 0) {
                if (authStore.hasRole(requiredRoles)) {
                    next(); // 权限匹配，放行
                } else {
                    // 角色不匹配，提示并跳转到首页
                    ElMessage.warning('您没有权限访问此页面');
                    next({ name: 'Home' });
                }
            } else {
                next(); // 路由需要认证但不需要特定角色，直接放行
            }
        } else {
            // 用户未登录，重定向到登录页
            next({ name: 'Login', query: { redirect: to.fullPath } });
        }
    } else {
        // 如果路由不需要认证，直接放行
        next();
    }
});

export default router;
